import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.io.File;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;


public class ToolsGui {
	
	public static void remplirTree(File dossier, DefaultMutableTreeNode racine, JTree tree  ) {
	 	 
	 	for(File file : dossier.listFiles()) {
	 	  
		 	 String fileName = file.getName();
		 	 System.out.println();
		 	 DefaultMutableTreeNode noeudTree = new DefaultMutableTreeNode(fileName);
		 	  
		 	 try {
			 	 for(File nom : file.listFiles()){
			  
			 	 DefaultMutableTreeNode node = new DefaultMutableTreeNode(nom.getName());
			 	 noeudTree.add(listFile(nom, node));
			  
			 	 }
		 	 } catch (NullPointerException e) {}
		 	  
		 	 racine.add(noeudTree);
	 	}
	 	 
	 	tree.setModel(new DefaultTreeModel(racine));
	 	tree.updateUI();
	 }
	  
	 public static DefaultMutableTreeNode listFile(File file, DefaultMutableTreeNode node) {
	 	 
	 	if(file.isFile())
	 	 return new DefaultMutableTreeNode(file.getName());
	 	else {
	 	  
	 	 for (File nom : file.listFiles()) {
	 	 DefaultMutableTreeNode subNode;
	 	 if (nom.isDirectory()) {
	 	 subNode = new DefaultMutableTreeNode(nom.getName() + "\\");
	 	 node.add(listFile(nom, subNode));
	 	 } else {
	 	 subNode = new DefaultMutableTreeNode(nom.getName());
	 	 }
	  
	 	 node.add(subNode);
	 	 }
	 	  
	 	 return node;
	 	}
	 }
	 
	 public static void doMouseClicked(MouseEvent me, JTree tree) {
		 if ( SwingUtilities.isRightMouseButton ( me ) )
         {
			
			 TreePath path = tree.getPathForLocation ( me.getX (), me.getY () );
             if (path != null) System.out.println(path.toString());
             
             
             
             Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
             if ( pathBounds != null && pathBounds.contains ( me.getX (), me.getY () ) )
             {
                 JPopupMenu menu = new JPopupMenu ();
                 menu.add ( new JMenuItem ( "Delete" ) );
                 menu.show ( tree, pathBounds.x+30, pathBounds.y + pathBounds.height );
             }
         } 		    
	}


}
